package com.fingard.dsp.bank.directbank.psbc11;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.ITcpClient;
import com.fingard.net.TcpPortClient;
import com.fingard.net.TcpReceiver;
import com.fingard.text.StringHelper;
import com.fingard.util.TransIDHelper;
import com.fingard.xml.XmlTextWriter;

import java.io.File;
import java.util.Date;

public class PSBC11Base extends DirectBase implements ITcpClient {
	protected String getCharset() {
		return getBankConfig().getCharset("GBK");
	}
	
	private static TransIDHelper idHelper = new TransIDHelper(1, 99);

    protected String getQryTransID() {
        Date tmpDateNow = new Date();
        return Format.Time6Format.format(tmpDateNow) + idHelper.getNextIDStr();
    }
	
	protected void writeCommonHeader(XmlTextWriter xmlWriter, PSBC11Header tmpBankHeader) {
        xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"" + getCharset() + "\"?>");
        xmlWriter.writeStartElement("REQUEST");
        xmlWriter.writeStartElement("MAIN");
        xmlWriter.writeElementString("TRANCD", tmpBankHeader.transCode);
        xmlWriter.writeElementString("INSUID", bankFront.corpNo);
        xmlWriter.writeElementString("TRANSRNO", tmpBankHeader.reqSeqID);
        xmlWriter.writeElementString("TRANSRDATE", Format.Date8Format.format(new Date()));
        xmlWriter.writeElementString("TRANSRTIME", Format.Time6Format.format(new Date()));
        xmlWriter.writeElementString("TERMID", getBankConfig().getValueAsString("termID"));
        xmlWriter.writeEndElement();
    }
	
	/**
	 * 获取批次顺序号
	 * 
	 * @param p_reqDir
	 * @return
	 */
	protected int getBatSeqNo(String p_reqDir) {
		int batSeqNo = -1;
		File tmpFileDir = new File(p_reqDir);
		if (tmpFileDir.exists()) {
			File[] tmpFileList = tmpFileDir.listFiles();
			if (tmpFileList != null) {
				batSeqNo = tmpFileList.length + 1;
			} else {
				batSeqNo = 1;
			}
		} else {
			batSeqNo = 1;
		}
		return batSeqNo;
	}
	
	/**
	 * 发送通知报文到银行
	 * 
	 * @param p_reqStr 银行请求报文
	 * @return 银行响应报文
	 * @throws Exception
	 */
	protected String[] sendToBank(String p_reqStr) throws Exception {
		String[] tmpStrRet = new String[] { "", "" };
		String str[] = p_reqStr.split("\\|");
		String[] strname = { "交易类型码", "保险公司代码", "保险公司类型", "保险公司交易日期", "保险公司文件的流水号", "批量文件名", "总笔数", "总金额", "文件校验码" };
		for (int i = 0; i < str.length; i++) {
			if (StringHelper.isNullOrEmpty(str[i])) {
				throw new Exception("未赋值：" + strname[i]);
			}
		}
		// 消息报文
		WriteBankLogStep2(p_reqStr);
		TcpPortClient tmpClient = new TcpPortClient(bankFront.serverIP, Integer.parseInt(bankFront.serverPort), this);
        int realSleepTime =100 ;
        if (getBankConfig().getValueAsInt("notifyWatiTime")>0) {
            realSleepTime = getBankConfig().getValueAsInt("notifyWatiTime");
        }
        WriteBankLogLn("超时时间："+realSleepTime);
        tmpClient.timeoutMil = realSleepTime*1000;
		WriteBankLogLn("服务地址：[" + bankFront.serverIP + ":" + bankFront.serverPort + "]");
		TcpReceiver tmpReceiver = tmpClient.sendMessage(p_reqStr.getBytes(getCharset()));
		tmpStrRet[0] = tmpReceiver.connState;
		if (tmpReceiver.recBytes != null) {
			String tmpStrResp = new String(tmpReceiver.recBytes, 0, tmpReceiver.readedLength, getCharset());
			if (tmpStrResp.contains("<")) {
				tmpStrRet[1] = tmpStrResp.substring(tmpStrResp.indexOf("<"));
			}else{
                tmpStrRet[1]= tmpStrResp;
            }
		}else {
            tmpStrRet[1] = tmpReceiver.getConnMsg();
        }
		WriteBankLogStep3(tmpStrRet[1]);
		if (!tmpReceiver.isCompleted) {
			WriteBankLogLn(tmpReceiver.getConnMsg());
		}
		return tmpStrRet;
	}
	
	/**
	 * 实时收款交易发送
	 * 
	 * @param p_reqStr
	 * @param transCode
	 * @return
	 * @throws Exception
	 */
	protected String[] sendToBank(String p_reqStr, String transCode) throws Exception {
		String[] tmpStrRet = new String[] { "", "" };

		String tmpReqMsgHeader = "POST" + transCode + String.format("%06d", p_reqStr.getBytes(getCharset()).length);
		String tmpReqStr = tmpReqMsgHeader + p_reqStr;
		WriteBankLogStep2(tmpReqStr);

		String serverPort = bankFront.serverPort;
		if ("816090".equals(transCode) || "816092".equals(transCode)) {
		    WriteBankLogLn("当前为单笔实时交易...");
		    boolean useRealTimePort = getBankConfig().getValueAsBool("useRealTimePort");
		    WriteBankLogLn("单笔实时是否启用单独的端口进行交易发送:" + useRealTimePort);
		    if (useRealTimePort) {
                serverPort = bankFront.filePort;
                WriteBankLogLn("单笔实时新交易端口为:" + serverPort);
            }
        }
		TcpPortClient tmpClient = new TcpPortClient(bankFront.serverIP, Integer.parseInt(serverPort), this);
		WriteBankLogLn("服务地址：[" + bankFront.serverIP + ":" + serverPort + "]");
		TcpReceiver tmpReceiver = tmpClient.sendMessage(tmpReqStr.getBytes(getCharset()));
		tmpStrRet[0] = tmpReceiver.connState;
		if (tmpReceiver.recBytes != null) {
			tmpStrRet[1] = new String(tmpReceiver.recBytes, 0, tmpReceiver.readedLength, getCharset());
		} else {
			tmpStrRet[1] = tmpReceiver.getConnMsg();
		}
		WriteBankLogStep3(tmpStrRet[1]);
		if (tmpStrRet[1].contains("<")) {
			tmpStrRet[1] = tmpStrRet[1].substring(tmpStrRet[1].indexOf('<'));
		}
		if (!tmpReceiver.isCompleted) {
			WriteBankLogLn(tmpReceiver.getConnMsg());
		}
		return tmpStrRet;
	}

	@Override
	public void getContentLength(TcpReceiver p_receiver) throws Exception {
	    String tmpPlainText = new String(p_receiver.recBytes, getCharset()).trim();
	    WriteBankLogLn("接收银行原始响应报文内容为:\r\n"+tmpPlainText);

        if (getBankConfig().getValueAsBool("notifyGH")) {
            // 国华人寿个性化响应解析
            //p_receiver.contentLength = Integer.parseInt(new String(p_receiver.recBytes, 5, 3, getCharset()));
            //p_receiver.contentStartIndex = 15;
        }  else {
            if (p_receiver.contentLength == -1&&p_receiver.readedLength >= 16) {
                p_receiver.contentLength = Integer.parseInt(new String(p_receiver.recBytes, 10, 6, getCharset()));
                p_receiver.contentStartIndex = 16;
            }
        }
	}
}